<template>
  <div>
    <a-row :gutter="[20, 20]">
      <a-col :span="24">
        <a-card>
          <a-row>
            <a-col :span="10">
              <a-input id="inputNumber" v-model:value="College" :min="1" :max="12" placeholder="请输入内容" />
            </a-col>
            <a-col :span="3">
              <a-button @click="search">确认</a-button></a-col>
            <a-col :span="3">
              <a-select v-model:value="Sorts">
                <a-select-option value="byTime">按时间排序</a-select-option>
                <a-select-option value="character">按字母排序</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="3">
              <a-select v-model:value="times">
                <a-select-option value="all">全部的</a-select-option>
                <a-select-option value="threeMonth">近3月</a-select-option>
                <a-select-option value="aYear">近一年</a-select-option>
              </a-select>
            </a-col>
          </a-row>
          <a-list>
            <a-list-item class="list">
              <a-list-item-meta class="opp">
                <template #description>
                  <a-row>
                    <a-col :span="2">
                      文件名
                    </a-col>
                    <a-col :span="1">
                      年份</a-col>
                    <a-col :span="1">
                      月份</a-col>
                    <a-col :span="2">
                      社团名称</a-col>
                    <a-col :span="2">
                      指导教师</a-col>
                    <a-col :span="2">
                      学院</a-col>
                    <a-col :span="2" :offset="8">
                      操作</a-col>
                  </a-row>
                </template></a-list-item-meta></a-list-item>
                 <template>
                  <div v-for="item in filteredList" :keys="item.id">
              <a-list-item class="list">
                <a-list-item-meta class="aaa">
                  <template #description>
                    <a-row>
                      <a-col :span="2">
                        {{ item.name }}
                      </a-col>
                      <a-col :span="1">
                        {{ item.year }}
                      </a-col>
                      <a-col :span="1">
                        {{ item.month }}
                      </a-col>
                      <a-col :span="2">
                        {{ item.society }}
                      </a-col>
                      <a-col :span="2">
                        {{ item.teacher }}
                      </a-col>
                      <a-col :span="2">
                        {{ item.institute }}
                      </a-col>
                      

                      <a-col :span="2" :offset="8" v-if="ifNotYet">
                        <a @click="openNotYetPdf(item.id)">打开pdf</a></a-col>
                      <a-col :span="2" :offset="8" v-else>
                        <a @click="openPdf(item.id)">打开pdf</a></a-col>
                      <a-col :span="2">
                        <a @click="downloadPdf(item.id)">下载pdf</a></a-col>

                    </a-row>
                  
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </div>
            </template>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
    <seePdf @register="register4" />
    <notYetPdf @register="register5" />
  </div>
</template>
<script lang="ts" setup>
import { Ref, ref, watch, nextTick, defineProps } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import {
  Card as ACard, Row as ARow, List as AList, Col as ACol,
  ListItem as AListItem, ListItemMeta as AListItemMeta, Input as AInput,
  Select as ASelect, SelectOption as ASelectOption
} from 'ant-design-vue';
enum Api {
  pdfList = '/pdflists'
}
const props = defineProps({
  //子组件接收父组件传递过来的值
  whichList: null,
  ifNotYet: {
    type: Boolean,
    default: false
  }
})
const pdfListApi = (params: any = null) =>defHttp.get({ url: Api.pdfList, params });
const Sorts = ref<string>('byTime');
const times = ref<string>('all');
let cardList: any = undefined
let parames = { whichList: props.whichList }
let College: Ref<string> = ref("")
const filteredList: Ref<any> = ref(cardList);
const search = () => {
  filteredList.value = cardList.filter(item => {
    return item.name.toLowerCase().includes(College.value.toLowerCase());
  });
};
nextTick(async () => {
  await pdfListApi(parames).then((result) => {
    cardList = result
    //我也不知道为啥会多下面这一行，但是不这么就会出错    
    filteredList.value = result;
  }).catch((error) => {
    console.error("失败：" + error); // 输出失败的原因
  })
})
watch(Sorts, (newValue) => {
  // console.log(`count changed from ${oldValue} to ${newValue}`);
  if (newValue == "character") {
    filteredList.value.sort((a, b) => {
      const nameA = a.name.toUpperCase(); // 不区分大小写
      const nameB = b.name.toUpperCase(); // 不区分大小写

      if (nameA < nameB) {
        return -1;
      }
      if (nameA > nameB) {
        return 1;
      }

      return 0; // 名字相同，不需要变换位置
    });
  }
  else if (newValue == "byTime") {
    filteredList.value.sort((a, b) => {
      const monthA = a.month
      const monthB = b.month

      if (monthA < monthB) {
        return -1;
      }
      if (monthA > monthB) {
        return 1;
      }

      return 0; // 名字相同，不需要变换位置
    });
  }


});
function filterRecentXMonths(data, currentDate, x) {
  // 获取当前日期的年份和月份
  const currentYear = currentDate.getFullYear();
  const currentMonth = currentDate.getMonth() + 1; // 月份从0开始，需要加1

  // 计算X个月前的年份和月份
  let threeMonthsAgoYear = currentYear;
  let threeMonthsAgoMonth = currentMonth - x;
  if (threeMonthsAgoMonth <= 0) {
    // 如果月份小于等于0，需要借位
    threeMonthsAgoYear--;
    threeMonthsAgoMonth += 12;
  }

  // 过滤数据
  const filteredData = data.filter(obj => {
    // 检查是否在近三个月内
    if (
      obj.year > threeMonthsAgoYear ||
      (obj.year === threeMonthsAgoYear && obj.month >= threeMonthsAgoMonth)
    ) {
      return true;
    }
    return false;
  });

  return filteredData;
}

watch(times, (newValue) => {
  // 获取当前日期
  const currentDate = new Date();
  // 获取当前月份
  const currentMonth = currentDate.getMonth() + 1; // 月份从0开始，所以需要加1
  if (newValue == "all") {
    filteredList.value = cardList
  }
  else if (newValue == "threeMonth") {
    console.log("currentMonth", currentMonth,);
    filteredList.value = filterRecentXMonths(cardList, currentDate, 3);

  }
  else if (newValue == "aYear") {
    filteredList.value = filterRecentXMonths(cardList, currentDate, 12);
  }
});
import seePdf from './seePdf.vue';
import { useDrawer } from '/@/components/Drawer';
const [register4, { openDrawer: openDrawer4 }] = useDrawer();
function openPdf(id: number) {
  openDrawer4(true, {
    data: 'content',
    id: id,
  });
}
import notYetPdf from './administrator/pdf.vue';
const [register5, { openDrawer: openDrawer5 }] = useDrawer();
function openNotYetPdf(id: number) {
  openDrawer5(true, {
    data: 'content',
    id: id,
  });
}
import axios from 'axios';
function downloadPdf(id:number) {
  // 替换为你的服务器端PDF文件路径
  const pdfUrl = 'http://127.0.0.1:3100/pdf';
  // 待会这里改成axios组件而非axios原生
  // 使用Axios发送GET请求
  // 发起 GET 请求并下载文件
  axios({
    method: 'get',
    url: pdfUrl,
    responseType: 'blob', // 设置响应数据的类型为二进制数据
    params: {
      id:id
    },
  })
    .then((response) => {
      // 创建一个 Blob 对象
      const blob = new Blob([response.data]);

      // 创建一个下载链接
      const downloadLink = document.createElement('a');
      downloadLink.href = window.URL.createObjectURL(blob);

      // 设置下载链接的属性
      downloadLink.download = '未命名.pdf'; // 你要保存的文件名及扩展名

      // 将下载链接附加到文档中
      document.body.appendChild(downloadLink);

      // 触发点击事件以启动下载
      downloadLink.click();

      // 移除下载链接
      document.body.removeChild(downloadLink);
    })
    .catch((error) => {
      // 处理错误
      console.error(error);
    });
}
</script>
<style scoped>
.list:nth-child(odd) {
  background-color: rgb(231, 231, 231);
  /* 设置奇数行的背景颜色 */
}
</style>